package com.genius.workflow.config;

import com.alibaba.fastjson.JSONObject;
import com.genius.adminmanager.other.entity.ResponseJson;
import org.apache.shiro.util.StringUtils;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.util.ArrayList;

public class ShiroFormAuthenticationFilter extends FormAuthenticationFilter {

    public static final String DEFAULT_PATH_SEPARATOR = "/";

    private String pathSeparator = DEFAULT_PATH_SEPARATOR;
    private ArrayList<String> apiUrls = new ArrayList<>();
    public ShiroFormAuthenticationFilter(String apiUrls){
        if(org.apache.commons.lang3.StringUtils.isNotBlank(apiUrls)){
            String [] apiUrlsArr = apiUrls.split(DefaultConfiguration.separator_douhao);
            for(String api:apiUrlsArr){
                this.apiUrls.add(api.replace("/**",""));
            }
        }
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (isLoginRequest(request, response)) {
            if (isLoginSubmission(request, response)) {
                return executeLogin(request, response);
            } else {
                return true;
            }
        } else {
            String requestURI = getPathWithinApplication(request);
            HttpServletRequest httpServletRequest = (HttpServletRequest)request;
            String[] pattDirs = StringUtils.tokenizeToStringArray(requestURI, this.pathSeparator);
            //是ajax请求重定向
            if(isAjax(request)){
                PrintWriter out = response.getWriter();
                JSONObject json = new JSONObject();
                json.put(ResponseJson.code,ResponseJson.session_timeout);
                out.println(json);
            }else{
                //针对前段请求window.location.href
                if(requestURI!=null&&requestURI.contains("/doc")){
                    response.setContentType("textml;charset=gb2312");
                    PrintWriter out = response.getWriter();
                    out.println("<script language='javascript' type='text/javascript'>");
                    out.println("alert('由于你长时间没有操作,导致Session失效!请你重新登录!');top.location.href='"+httpServletRequest.getContextPath()+"/tologin'");
                    out.println("</script>");
                }else {
                    //针对Form表单提交
                    this.saveRequestAndRedirectToLogin(request, response);
                }
            }

            return false;
        }
    }
    private boolean isAjax(ServletRequest request){
        HttpServletRequest httpRequest = (HttpServletRequest)request;
        String servletPath = httpRequest.getServletPath();
        String header = httpRequest.getHeader("X-Requested-With");
        if("XMLHttpRequest".equalsIgnoreCase(header) && !isStartWithApi(servletPath) ){
            return true;
        }
        return false;
    }
    private boolean isStartWithApi(String url){
        boolean isStartWith = false;
        for(String apiUrl:apiUrls){
            if(url.startsWith(apiUrl)){
                isStartWith = true;
                break;
            }
        }
        return isStartWith;
    }
}
